package com.yun.baymax.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.hyphenate.easeui.EaseConstant;
import com.yun.baymax.R;
import com.yun.baymax.adapter.CommentAdapter;
import com.yun.baymax.adapter.TrendsDetailAdapter;
import com.yun.baymax.bean.User;
import com.yun.baymax.bean.adapter.Comment;
import com.yun.baymax.bean.adapter.Trends;
import com.yun.baymax.utils.GlideUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobPointer;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

public class ItemActivity extends BaseActivity {
    @BindView(R.id.et_comment)
    EditText etComment;
    @BindView(R.id.tv_publish)
    TextView tvPublish;
    @BindView(R.id.iv_vote)
    CheckBox ivVote;
    @BindView(R.id.iv_favorite)
    CheckBox ivFavorite;

    @BindView(R.id.head_view)
    ImageView headView;
    @BindView(R.id.add)
    ImageView add;
    @BindView(R.id.bar_background)
    ImageView barBackground;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.state)
    TextView state;
    @BindView(R.id.content)
    TextView content;
    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.recycler_comment)
    RecyclerView cRecyclerView;

    private Trends trend;
    private TrendsDetailAdapter adapter;
    private User currentUser;
    private CommentAdapter commentAdapter;
    private List<Comment> comments = new ArrayList<>();


    @Override
    protected int setLayoutResourceId() {
        return R.layout.activity_item;
    }

    @Override
    protected void initVariables() {
        ButterKnife.bind(this);
        trend = (Trends) getIntent().getSerializableExtra("trend");
        currentUser = BmobUser.getCurrentUser(User.class);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle(trend.title);
        setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.drawable.ic_arrow_back);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        etComment.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s)) {
                    tvPublish.setVisibility(View.VISIBLE);
                    ivFavorite.setVisibility(View.GONE);
                    ivVote.setVisibility(View.GONE);
                } else {
                    tvPublish.setVisibility(View.GONE);
                    ivFavorite.setVisibility(View.VISIBLE);
                    ivVote.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        LinearLayoutManager gridManager = new LinearLayoutManager(mContext);
        mRecyclerView.setLayoutManager(gridManager);
        adapter = new TrendsDetailAdapter(mContext, trend.pics, 0);
        mRecyclerView.setAdapter(adapter);

        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        cRecyclerView.setLayoutManager(layoutManager);
        commentAdapter = new CommentAdapter(mContext, null);
        cRecyclerView.setAdapter(commentAdapter);

    }

    @Override
    protected void loadData() {
        User author = trend.author;
        if (!TextUtils.isEmpty(author.getHeadImage()))
            Glide.with(mContext).load(author.getHeadImage()).asBitmap().into(GlideUtils.setCircle(mContext, headView));
//        if (!TextUtils.isEmpty(trend.avatar))
//            Glide.with(mContext).load(trend.avatar).into(barBackground);
        name.setText(author.getNick());
        state.setText(author.getContent());
        content.setText(trend.content);
        if (trend.votes != null)
            ivVote.setSelected(trend.votes.contains(currentUser.getUserName()));


        BmobQuery<Comment> commentQuery = new BmobQuery<>();
        commentQuery.addWhereEqualTo("trends", new BmobPointer(trend));
        commentQuery.include("user");
        commentQuery.findObjects(new FindListener<Comment>() {
            @Override
            public void done(List<Comment> list, BmobException e) {
                if (e == null) {
                    commentAdapter.setDatas(list);
                    comments = list;
                } else {
                    Log.i("YUN", "comment find fail");
                }
            }
        });

    }

    @OnClick({R.id.add, R.id.state, R.id.name, R.id.head_view, R.id.tv_publish, R.id.iv_favorite, R.id.iv_vote})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.add:
                Intent intent1 = new Intent(mContext, ChatActivity.class).putExtra(EaseConstant.EXTRA_USER_ID, trend.author.getHxName());
                intent1.putExtra("nick", trend.author.getNick());
                startActivity(intent1);
                break;
            case R.id.head_view:
            case R.id.name:
            case R.id.state:
                Intent intent = new Intent(mContext, ProfileActivity.class);
                if (trend.author == null)
                    return;
                intent.putExtra("user", trend.author);
                startActivity(intent);
                break;
            case R.id.tv_publish:
                publishComment(etComment.getText().toString());
                break;
            case R.id.iv_vote:
                voteOrFavor(ivVote);
                break;
            case R.id.iv_favorite:
                voteOrFavor(ivFavorite);
                break;
            default:
                break;
        }
    }

    private void voteOrFavor(CheckBox cb) {
        if (cb.isSelected()) {
            cb.setSelected(false);
            trend.votes.remove(currentUser.getUserName());
        } else {
            cb.setSelected(true);
            trend.votes.add(currentUser.getUserName());
        }

        trend.update(new UpdateListener() {
            @Override
            public void done(BmobException e) {

            }
        });
    }

    private void publishComment(final String comment) {
        final Comment mComment = new Comment();
        mComment.comment = comment;
        mComment.trends = trend;
        mComment.user = currentUser;
        mComment.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null) {
                    Toast.makeText(ItemActivity.this, "留言成功", Toast.LENGTH_SHORT).show();
                    comments.add(mComment);
                    commentAdapter.setDatas(comments);

                    etComment.setText("");
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(etComment.getWindowToken(), 0); //强制隐藏键盘
                    cRecyclerView.scrollToPosition(comments.size() - 1);
                } else {
                    Toast.makeText(ItemActivity.this, "留言失败:" + e.toString(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_trend_item, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Toast.makeText(ItemActivity.this, "额，分享还没做好啊", Toast.LENGTH_SHORT).show();
        return super.onOptionsItemSelected(item);
    }
}

